<template>
  <div class="page">
    <tree-list
      :path="selectPath"
      show-search
      @folder-select="folderSelect"
      @file-select="fileSelect"
    ></tree-list>
    <div v-loading="loading" class="content-wrapper">
      <c-card v-if="selectPath" title="历史数据">
        <div class="search-row">
          <div>
            <div class="item">
              <label>应用类型</label>
              <el-select v-model="variabletype" size="small" @change="_getHisData">
                <el-option label="全部" :value="null"></el-option>
                <el-option v-for="(s, i) in statusList" :key="i" :value="i + 1" :label="s"></el-option>
              </el-select>
            </div>
            <div class="item">
              <label>选择日期</label>
              <el-date-picker
                v-model="dateOpt"
                type="daterange"
                align="right"
                size="small"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="_getHisData"
              ></el-date-picker>
            </div>
            <div class="item">
              <label>粒度区间</label>
              <el-select v-model="interval" size="small" @change="_getHisData">
                <el-option v-for="(s, i) in [5, 10, 15, 30, 60]" :key="i" :value="s" :label="s"></el-option>
              </el-select>
            </div>
            <!-- <el-button class="item" size="small" @click="_getHisData">查询</el-button> -->
          </div>
        </div>
        <transition name="el-fade-in-linear">
          <div id="echarts" class="echarts" style="height: 300px;"></div>
        </transition>
        <el-table ref="table" :data="params" style="width: 100%">
          <el-table-column width="50">
            <template v-slot="{row}">
              <input v-model="curId" type="radio" :value="row.pkid" />
            </template>
          </el-table-column>
          <el-table-column label="序号">
            <template v-slot="{$index}">
              <span>{{ page.size * (page.index - 1) + $index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="variablename" label="变量名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="variabletype" label="变量类型"></el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page.sync="page.index"
            :total="page.total"
            @current-change="_getParams"
          ></el-pagination>
        </div>
      </c-card>
      <h3 v-else style="text-align: center">请先选择厂站...</h3>
    </div>
  </div>
</template>

<script>
import TreeList from "./components/TreeList";
import CCard from "@/components/CCard";
import { getParams, getHisData } from "../../api/device";
import {
  parseTime,
  compareTime,
  getLastDayOfMonth,
  calcPageNum
} from "../../utils";
import echarts from "echarts";
const now = parseTime(new Date(), "{y}-{m}-{d}");
export default {
  name: "HistoryData",
  components: {
    TreeList,
    CCard
  },
  data() {
    return {
      loading: false,
      realData: null,
      selectPath: [],
      status: null,
      dateOpt: [now, now],
      params: null,
      curId: null,
      page: {
        index: 1,
        total: 0,
        size: 16
      },
      statusList: ["遥信", "遥测"],
      variabletype: null,
      interval: 10,
      echarts: null,
      pickerOptions: {
        disabledDate: function(v) {
          return compareTime(v, now) >= 0;
        }
      }
    };
  },
  watch: {
    curId(id) {
      if (id) {
        this._getHisData();
      }
    },
    dateOpt(d) {
      const [s, e] = d;
      if (!e || !s) {
        return;
      } else {
        const sm = new Date(s).getMonth();
        const em = new Date(e).getMonth();
        if (sm !== em) {
          const ee = parseTime(getLastDayOfMonth(s), "{y}-{m}-{d}");
          this.$set(this.dateOpt, 1, ee);
        }
      }
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (to.fullPath !== from.fullPath) {
      const path = to.query.path;
      this.selectPath = path && path.split(",");
      if (path) {
        this.$nextTick(() => {
          this._getParams().then(() => {
            this.params && (this.curId = this.params[0].pkid);
          });
        });
      }
    }
    next();
  },
  mounted() {
    const path = this.$route.query.path;
    this.selectPath = path && path.split(",");
    path &&
      this._getParams().then(() => {
        this.params && (this.curId = this.params[0].pkid);
      });
  },
  methods: {
    _getParams() {
      const h = this.$refs["table"].$el.clientHeight;
      const n = calcPageNum(h);
      this.$set(this.page, "size", n);

      const idstr = this.selectPath[this.selectPath.length - 1];
      const id = parseInt(idstr.substr(1));
      return getParams(id, this.page.size, this.page.index)
        .then(res => {
          this.params = res.rows;
          this.$set(this.page, "total", res.total);
        })
        .catch(() => (this.curId = null));
    },
    _getHisData() {
      const params = {
        paramId: this.curId,
        variabletype: this.variabletype,
        interval: this.interval,
        startTime: this.dateOpt[0],
        endTime: this.dateOpt[1]
      };
      this.loading = true;
      if (!this.echarts) {
        this.echarts = echarts.init(document.getElementById("echarts"));
      }
      return getHisData(params)
        .then(data => {
          if (!data || JSON.stringify(data) === "{}") {
            this.setOption({});
            return this.$message.warning("历史数据为空...");
          }
          this.setOption(data);
        })
        .catch(e => this.setOption({}))
        .finally(() => (this.loading = false));
    },
    setOption({ header, list }) {
      const [xData, data] = [header, []];
      let [min, max] = [0, 0];
      list && list.forEach(e => {
        min = e.min < min ? e.min : min;
        max = e.max > max ? e.max * 1.05 : max;
        const o = {
          type: "line",
          name: e.day + "日",
          data: e.datas
        };
        data.push(o);
      });
      const options = {
        legend: {
          top: 10
        },
        grid: {
          top: 40,
          left: 50,
          right: 20,
          bottom: 40
        },
        tooltip: {
          trigger: "axis"
        },
        xAxis: {
          type: "category",
          data: xData
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: false
          },
          min: min || 0,
          max: max || 1
        },
        series: data
      };
      this.echarts.setOption(options, true);
    },
    folderSelect(path) {
      // const urlPath = this.$route.path;
      // this.selectPath = path;
      // this.$router.push(urlPath + "?path=" + path.join(","));
    },
    fileSelect(path) {
      const urlPath = this.$route.path;
      // this.selectPath = path;
      this.$router.push(urlPath + "?path=" + path.join(","));
    },
    startChange(s) {}
  }
};
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
}
.tree {
  position: absolute;
  width: 275px;
  height: 100%;
  overflow-y: auto;
  background: #222c3c;
  box-sizing: border-box;
}
</style>
